<?php
/**
 * Created by PhpStorm.
 * User: Rain
 * Date: 2020/5/16
 * Time: 13:44
 */

namespace app\admin\service\business\controllers\Ad\Cate;


use app\admin\service\business\BaseControllerService;
use app\admin\service\business\controllers\Ad\Cate\Models\AdCateModel;

/**
 * Class AdCateService
 *
 * @property-read AdCateModel $model
 *
 * @package app\admin\service\business\controllers\Ad\Cate
 */
class AdCateService extends BaseControllerService
{
    protected $rely = [
        'model' => AdCateModel::class,
    ];

    /**
     * 查询列表
     *
     * @param array $where
     * @param int $limit
     * @return mixed
     */
    public function resList(array $where, int $limit)
    {
        $list = $this -> model -> getList($where['key'] ?? [], [], true, $limit);

        return $list;
    }

    /**
     * 查询单条信息
     *
     * @param int $id
     * @return mixed
     */
    public function resFind(int $id)
    {
        $result = $this->model->getFind($id);

        return $result;
    }

    /**
     * 操作数据
     *
     * @param array $params
     * @param int $id
     * @return array
     */
    public function operating(array $params, int $id = 0): array
    {
        // 判断 name 是否重复
        if ($this->model->isUnique($params['name'], $id)) return echoArr(500, '当前名称已存在');

        // 需操作的数据
        $data = [
            'name' => $params['name'],
            'description' => $params['description']
        ];

        try {
            // 执行数据更新
            if ($id) {
                $this->model->edit($data, $id);
            } else {
                $this->model->insert($data);
            }
        } catch (\Exception $e) {
            return echoArr(800);
        }

        return echoArr(200);
    }


    /**
     * 删除数据
     *
     * @param int $id
     * @return array
     */
    public function del(int $id): array
    {
        // 当前分类是否有广告
        if($this -> model -> isAd($id)) return echoArr(500, '当前分类下已有广告，请先移除');

        try {
            // 删除广告
            $this -> model -> delete($id);
        } catch (\Exception $exception) {
            return echoArr(800);
        }

        return echoArr(200, '操作成功');
    }
}
